/**
 * @file ResourceAnalyzer.vue
 * @description 智能教学资源分析与分类组件，提供专业化分析界面
 * @created 2024-06-30
 */

<template>
  <div class="resource-analyzer">
    <el-dialog
      v-model="dialogVisible"
      title="教学资源智能分析"
      width="800px"
      :destroy-on-close="false"
    >
      <!-- 分析状态进度显示 -->
      <div v-if="analyzing" class="analyzing-state">
        <el-progress :percentage="analyzeProgress" :stroke-width="15">
          <span>{{ analyzingMessage }}</span>
        </el-progress>
        <p class="analyze-tip">正在智能分析资源内容，这可能需要几分钟时间...</p>
      </div>

      <!-- 文件上传区域 -->
      <div v-if="!analyzing && !analysisResult" class="upload-area">
        <div class="select-file-area">
          <el-upload
            :action="null"
            :http-request="uploadFile"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :accept="acceptedFileTypes"
            drag
          >
            <el-icon class="upload-icon"><upload-filled /></el-icon>
            <div class="el-upload__text">
              拖放文件到此处或 <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持PDF、PPT、Word、MP4文件，大小不超过100MB
              </div>
            </template>
          </el-upload>
        </div>
        <div class="analyze-type-selection">
          <h3>分析选项</h3>
          <el-checkbox-group v-model="analyzeOptions">
            <el-checkbox label="resource_type">资源类型识别</el-checkbox>
            <el-checkbox label="subject_area">学科领域判断</el-checkbox>
            <el-checkbox label="content_analysis">内容特点分析</el-checkbox>
            <el-checkbox label="value_assessment">教学价值评估</el-checkbox>
            <el-checkbox label="generate_tags">关键词标签生成</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>

      <!-- 分析结果展示区域 -->
      <div v-if="!analyzing && analysisResult" class="analysis-result">
        <div class="result-header">
          <h3>{{ resourceName }} - 分析结果</h3>
          <el-rate v-model="analysisResult.score" disabled />
        </div>

        <!-- 标签展示 -->
        <div class="result-section tags-section">
          <h4>智能标签</h4>
          <div class="tags-container">
            <el-tag 
              v-for="tag in analysisResult.tags" 
              :key="tag.name"
              :type="getTagType(tag.confidence)"
              class="tag-item"
            >
              {{ tag.name }}
              <span class="confidence">({{ Math.round(tag.confidence * 100) }}%)</span>
            </el-tag>
          </div>
        </div>

        <!-- 分类信息 -->
        <div class="result-section category-section">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="主分类">
              {{ analysisResult.mainCategory || '未识别' }}
            </el-descriptions-item>
            <el-descriptions-item label="子分类">
              {{ analysisResult.subCategory || '未识别' }}
            </el-descriptions-item>
            <el-descriptions-item label="学科领域">
              {{ analysisResult.subjectArea || '未识别' }}
            </el-descriptions-item>
            <el-descriptions-item label="资源类型">
              {{ getResourceTypeLabel(resourceType) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 教学价值评估 -->
        <div class="result-section value-section">
          <h4>教学价值评估</h4>
          <div class="value-content">
            {{ analysisResult.educationalValue || '暂无评估' }}
          </div>
        </div>

        <!-- 推荐用途 -->
        <div class="result-section uses-section">
          <h4>推荐用途</h4>
          <ul class="uses-list">
            <li v-for="(use, index) in analysisResult.recommendedUses" :key="index">
              {{ use }}
            </li>
          </ul>
          <div v-if="!analysisResult.recommendedUses || analysisResult.recommendedUses.length === 0" class="no-data">
            暂无推荐用途
          </div>
        </div>
      </div>

      <!-- 对话框底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">关闭</el-button>
          <el-button v-if="!analyzing && analysisResult" type="primary" @click="saveAnalysis">
            保存分析结果
          </el-button>
          <el-button v-if="!analyzing && !analysisResult" type="primary" @click="startAnalysis">
            开始分析
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { adminAiChat } from '@/api/ai'
import { uploadResource } from '@/api/resource'

// 对话框可见性控制，通过v-model绑定
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  resourceId: {
    type: Number,
    default: 0
  }
})

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 定义事件
const emit = defineEmits(['update:modelValue', 'analysis-complete'])

// 文件相关状态
const acceptedFileTypes = '.pdf,.ppt,.pptx,.doc,.docx,.mp4'
const selectedFile = ref(null)
const resourceName = ref('')
const resourceType = ref('')

// 分析状态
const analyzing = ref(false)
const analyzeProgress = ref(0)
const analyzeTimer = ref(null)
const analyzingMessage = ref('正在准备分析...')
const analysisResult = ref(null)

// 分析选项
const analyzeOptions = ref(['resource_type', 'subject_area', 'content_analysis', 'value_assessment', 'generate_tags'])

// 验证上传文件
const beforeUpload = (file) => {
  // 文件类型验证
  const allowedTypes = [
    'application/pdf',
    'application/vnd.ms-powerpoint',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'video/mp4'
  ]
  
  if (!allowedTypes.includes(file.type)) {
    ElMessage.error('文件类型不支持，请上传PDF、PPT、Word或MP4文件')
    return false
  }
  
  // 文件大小验证 (最大100MB)
  const maxSize = 100 * 1024 * 1024
  if (file.size > maxSize) {
    ElMessage.error('文件过大，请上传小于100MB的文件')
    return false
  }
  
  return true
}

// 上传文件处理
const uploadFile = async ({ file }) => {
  selectedFile.value = file
  resourceName.value = file.name
  
  // 根据文件类型确定资源类型
  const extension = file.name.split('.').pop().toLowerCase()
  if (['doc', 'docx', 'pdf', 'txt'].includes(extension)) {
    resourceType.value = 'document'
  } else if (['ppt', 'pptx'].includes(extension)) {
    resourceType.value = 'presentation'
  } else if (['mp4', 'avi', 'mov', 'wmv'].includes(extension)) {
    resourceType.value = 'video'
  } else {
    resourceType.value = 'other'
  }
  
  ElMessage.success(`已选择文件: ${file.name}`)
}

// 开始分析
const startAnalysis = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择要分析的文件')
    return
  }
  
  try {
    analyzing.value = true
    analyzeProgress.value = 0
    analyzingMessage.value = '正在上传文件...'
    
    // 模拟上传和分析进度
    analyzeTimer.value = setInterval(() => {
      if (analyzeProgress.value < 30) {
        analyzeProgress.value += 1
        analyzingMessage.value = '正在上传文件...'
      } else if (analyzeProgress.value < 60) {
        analyzeProgress.value += 0.5
        analyzingMessage.value = '正在识别资源内容...'
      } else if (analyzeProgress.value < 90) {
        analyzeProgress.value += 0.3
        analyzingMessage.value = '正在生成智能分析...'
      } else if (analyzeProgress.value < 99) {
        analyzeProgress.value += 0.1
        analyzingMessage.value = '即将完成分析...'
      }
    }, 100)
    
    // 上传文件
    const formData = new FormData()
    formData.append('file', selectedFile.value)
    formData.append('resource_name', resourceName.value)
    formData.append('creator_id', 1)
    formData.append('analyze_options', JSON.stringify(analyzeOptions.value))
    
    const uploadResult = await uploadResource(formData)
    if (uploadResult.status !== 'success') {
      throw new Error(uploadResult.message || '上传失败')
    }
    
    // 获取资源ID
    const resourceId = uploadResult.data?.resource_id
    if (!resourceId) {
      throw new Error('无法获取资源ID')
    }
    
    // 构造AI分析请求内容
    const analysisQuery = `分析这个教学资源:
文件名: ${resourceName.value}
资源类型: ${getResourceTypeLabel(resourceType.value)}
文件大小: ${(selectedFile.value.size / 1024 / 1024).toFixed(2)}MB

请按照以下要求进行分析:
1. 识别资源的类型（如课件、教案、试题、视频等）
2. 判断资源适用的学科领域
3. 分析内容特点和教学价值
4. 提取关键词并生成标签

请以JSON格式返回分析结果，包含以下字段:
{
  "tags": [
    {"name": "标签1", "confidence": 0.95},
    {"name": "标签2", "confidence": 0.87},
    {"name": "标签3", "confidence": 0.82}
  ],
  "mainCategory": "主分类",
  "subCategory": "子分类",
  "subjectArea": "学科领域",
  "educationalValue": "教学价值简要评估",
  "recommendedUses": ["推荐用途1", "推荐用途2"]
}

对于无法确定的字段，请保留但标注置信度较低。只返回JSON，不要有多余解释。`
    
    // 调用AI分析
    const aiResult = await adminAiChat({
      query: analysisQuery,
      file_info: `资源ID: ${resourceId}`,
      conversation_id: '',
      user_id: 'admin-analyst'
    })
    
    // 处理AI分析结果
    if (aiResult.data.status === 'success') {
      // 尝试从回答中提取JSON
      const answer = aiResult.data.data.answer || '{}'
      try {
        // 查找JSON部分
        const jsonStart = answer.indexOf('{')
        const jsonEnd = answer.lastIndexOf('}') + 1
        if (jsonStart >= 0 && jsonEnd > jsonStart) {
          const jsonStr = answer.substring(jsonStart, jsonEnd)
          const result = JSON.parse(jsonStr)
          
          // 增加评分计算
          result.score = calculateOverallScore(result)
          
          analysisResult.value = result
          
          // 通知父组件分析完成
          emit('analysis-complete', {
            resourceId,
            result
          })
        } else {
          throw new Error('无法从回答中提取JSON')
        }
      } catch (jsonError) {
        console.error('解析AI回答JSON出错:', jsonError)
        throw new Error('解析分析结果失败')
      }
    } else {
      throw new Error(aiResult.data.message || 'AI分析服务异常')
    }
  } catch (error) {
    console.error('资源分析错误:', error)
    ElMessage.error('分析失败: ' + error.message)
  } finally {
    // 清除计时器并完成进度
    clearInterval(analyzeTimer.value)
    analyzeProgress.value = 100
    analyzingMessage.value = '分析完成！'
    
    // 延迟关闭分析状态
    setTimeout(() => {
      analyzing.value = false
    }, 1000)
  }
}

// 计算总体评分
const calculateOverallScore = (result) => {
  // 初始评分为3.5(基础评分)
  let score = 3.5
  
  // 根据标签数量和置信度增加评分
  if (result.tags && result.tags.length > 0) {
    // 标签数量影响(最多加0.5分)
    score += Math.min(result.tags.length / 10, 0.5)
    
    // 标签置信度影响(最多加0.5分)
    const avgConfidence = result.tags.reduce((sum, tag) => sum + (tag.confidence || 0), 0) / result.tags.length
    score += avgConfidence * 0.5
  }
  
  // 根据是否有完整分类信息增加评分(最多加0.5分)
  if (result.mainCategory) score += 0.2
  if (result.subCategory) score += 0.2
  if (result.subjectArea) score += 0.1
  
  // 根据是否有教学价值和推荐用途增加评分(最多加0.5分)
  if (result.educationalValue && result.educationalValue.length > 10) score += 0.25
  if (result.recommendedUses && result.recommendedUses.length > 0) score += 0.25
  
  // 确保评分在1-5之间
  return Math.max(1, Math.min(5, score))
}

// 保存分析结果
const saveAnalysis = () => {
  ElMessage.success('分析结果已保存')
  closeDialog()
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  
  // 如果有分析结果，延迟重置状态，以便下次打开时保持结果
  if (analysisResult.value) {
    setTimeout(() => {
      selectedFile.value = null
      resourceName.value = ''
      resourceType.value = ''
      analysisResult.value = null
    }, 300)
  } else {
    // 如果没有分析结果，立即重置
    selectedFile.value = null
    resourceName.value = ''
    resourceType.value = ''
  }
}

// 获取标签类型（根据置信度）
const getTagType = (confidence) => {
  if (confidence >= 0.9) return 'success'
  if (confidence >= 0.7) return ''
  if (confidence >= 0.5) return 'warning'
  return 'info'
}

// 获取资源类型显示名称
const getResourceTypeLabel = (type) => {
  const typeMap = {
    'document': '文档资料',
    'presentation': '演示文稿',
    'video': '视频资源',
    'audio': '音频资源',
    'image': '图片资源',
    'other': '其他资源'
  }
  return typeMap[type] || '未知类型'
}

// 监听resourceId变化，如果提供了resourceId则加载已有资源
watch(() => props.resourceId, async (newVal) => {
  if (newVal > 0) {
    // 这里可以添加通过resourceId加载已有资源的逻辑
  }
}, { immediate: true })
</script>

<style scoped>
.resource-analyzer {
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
}

.analyzing-state {
  padding: 30px 20px;
}

.analyze-tip {
  text-align: center;
  color: #666;
  margin-top: 15px;
}

.upload-area {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.select-file-area {
  padding: 10px;
}

.upload-icon {
  font-size: 36px;
  color: #409EFF;
}

.analyze-type-selection {
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.analysis-result {
  padding: 5px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.result-section {
  margin-bottom: 20px;
  padding: 15px;
  border-radius: 4px;
  background-color: #f8f9fa;
}

.result-section h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #409EFF;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag-item {
  padding: 6px 10px;
  font-size: 13px;
}

.tag-item .confidence {
  font-size: 11px;
  opacity: 0.8;
  margin-left: 4px;
}

.value-content {
  line-height: 1.6;
}

.uses-list {
  padding-left: 20px;
  margin: 0;
}

.uses-list li {
  margin-bottom: 5px;
}

.no-data {
  color: #999;
  font-style: italic;
}
</style> 